<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="admin/layout/base :: html(~{::title}, ~{::#content}, ~{::script})">
<head>
    <title>回收员管理 - 废物回收管理系统</title>
    <!-- 添加必要的CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css" rel="stylesheet">
</head>
<body>
    <div id="content">
        <!-- 页面标题 -->
        <div class="page-title">
            <h4>回收员管理</h4>
        </div>

        <!-- 搜索栏 -->
        <div class="content-card mb-4">
            <form class="row g-3" id="searchForm">
                <div class="col-md-3">
                    <input type="text" class="form-control" placeholder="用户名/手机号" name="keyword" th:value="${keyword}" autocomplete="off">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary">
                        <i class="bx bx-search"></i> 搜索
                    </button>
                </div>
                <div class="col-md-2 ms-auto">
                    <button type="button" class="btn btn-success" onclick="showAddModal()">
                        <i class="bx bx-plus"></i> 添加回收员
                    </button>
                </div>
            </form>
        </div>

        <!-- 数据表格 -->
        <div class="content-card">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>真实姓名</th>
                            <th>手机号</th>
                            <th>服务区域</th>
                            <th>本月订单</th>
                            <th>总订单</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:each="collector : ${collectors}">
                            <td th:text="${collector.id}">1</td>
                            <td th:text="${collector.username}">collector001</td>
                            <td th:text="${collector.realName}">李四</td>
                            <td th:text="${collector.phone}">13900139000</td>
                            <td th:text="${collector.serviceArea ?: '未设置'}">朝阳区</td>
                            <td th:text="${collector.monthlyOrders != null ? collector.monthlyOrders : 0}">10</td>
                            <td th:text="${collector.totalOrders != null ? collector.totalOrders : 0}">100</td>
                            <td>
                                <span th:class="${'badge ' + (collector.status == 1 ? 'bg-success' : 'bg-danger')}"
                                      th:text="${collector.status == 1 ? '正常' : '禁用'}">
                                    正常
                                </span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-info" title="编辑" 
                                        th:onclick="'editCollector(' + ${collector.id} + ')'">
                                    <i class="bx bx-edit"></i>
                                </button>
                                <button th:if="${collector.status == 1}" class="btn btn-sm btn-warning" title="禁用"
                                        th:onclick="'updateStatus(' + ${collector.id} + ', 0)'">
                                    <i class="bx bx-block"></i>
                                </button>
                                <button th:if="${collector.status == 0}" class="btn btn-sm btn-success" title="启用"
                                        th:onclick="'updateStatus(' + ${collector.id} + ', 1)'">
                                    <i class="bx bx-check"></i>
                                </button>
                                <button class="btn btn-sm btn-primary" title="查看详情"
                                        th:onclick="'viewDetails(' + ${collector.id} + ')'">
                                    <i class="bx bx-detail"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 添加/编辑模态框 -->
        <div class="modal fade" id="collectorModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">添加回收员</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="collectorForm">
                            <input type="hidden" name="id">
                            <div class="mb-3">
                                <label class="form-label">用户名</label>
                                <input type="text" class="form-control" name="username" required autocomplete="username">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">密码</label>
                                <input type="password" class="form-control" name="password" autocomplete="new-password">
                                <small class="text-muted">编辑时留空表示不修改密码</small>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">真实姓名</label>
                                <input type="text" class="form-control" name="realName" required autocomplete="name">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">手机号</label>
                                <input type="tel" class="form-control" name="phone" required autocomplete="tel">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">服务区域</label>
                                <input type="text" class="form-control" name="serviceArea" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveCollector()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加必要的JavaScript依赖 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.all.min.js"></script>
    
    <script th:fragment="script" type="text/javascript">
        // 定义所有函数
        function showAddModal() {
            const form = document.getElementById('collectorForm');
            if (form) {
                form.reset();
                form.querySelector('input[name="id"]').value = '';
                document.querySelector('.modal-title').textContent = '添加回收员';
                const modal = new bootstrap.Modal(document.getElementById('collectorModal'));
                modal.show();
            }
        }

        function editCollector(id) {
            if (!id) return;
            
            $.ajax({
                url: '/admin/collectors/' + id,
                method: 'GET',
                success: function(response) {
                    if (response && response.data) {
                        const collector = response.data;
                        const form = document.getElementById('collectorForm');
                        if (!form) return;
                        
                        // 只设置表单中存在的字段
                        const fields = ['id', 'username', 'realName', 'phone', 'serviceArea'];
                        fields.forEach(field => {
                            const input = form.querySelector(`[name="${field}"]`);
                            if (input) {
                                input.value = collector[field] || '';
                            }
                        });
                        
                        document.querySelector('.modal-title').textContent = '编辑回收员';
                        const modal = new bootstrap.Modal(document.getElementById('collectorModal'));
                        modal.show();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: '获取数据失败',
                            text: response.message || '未找到回收员信息'
                        });
                    }
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: '获取数据失败',
                        text: xhr.responseJSON?.message || '请稍后重试'
                    });
                }
            });
        }

        function updateStatus(id, status) {
            if (!id) return;

            Swal.fire({
                title: '确认' + (status === 1 ? '启用' : '禁用') + '该回收员？',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/admin/collectors/' + id + '/status',
                        method: 'POST',
                        data: { status: status },
                        success: function() {
                            Swal.fire({
                                icon: 'success',
                                title: '操作成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                window.location.reload();
                            });
                        },
                        error: function(xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: '操作失败',
                                text: '更新失败，请稍后重试'
                            });
                        }
                    });
                }
            });
        }

        function viewDetails(id) {
            if (!id) return;
            window.location.href = '/admin/collectors/' + id + '/details';
        }

        function saveCollector() {
            const form = document.getElementById('collectorForm');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());
            const id = data.id;
            const method = id ? 'PUT' : 'POST';
            const url = id ? `/admin/collectors/${id}` : '/admin/collectors';
            
            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function() {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('collectorModal'));
                    modal.hide();
                    
                    Swal.fire({
                        icon: 'success',
                        title: '保存成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        window.location.reload();
                    });
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: '保存失败',
                        text: xhr.responseJSON?.message || '请稍后重试'
                    });
                }
            });
        }

        // 页面加载完成后执行
        $(document).ready(function() {
            // 搜索表单提交
            $('#searchForm').on('submit', function(e) {
                e.preventDefault();
                const keyword = $(this).find('input[name="keyword"]').val();
                window.location.href = '/admin/collectors?keyword=' + encodeURIComponent(keyword);
            });
        });
    </script>
</body>
</html> 